function alightoevent_bgend(data_chan_by_t, events2, Fs)
assert(size(events2,2) == 2);
events_bg = events2(:,1); events_end = events2(:,2);
wds_in = 10*Fs; wds_out = 5*Fs;
[Alg_mean_bg,  Alg_cell_bg]  = aligntoevents(data_chan_by_t, events_bg,  -wds_out, wds_in);
[Alg_mean_end, Alg_cell_end] = aligntoevents(data_chan_by_t, events_end, -wds_in, wds_out);
% Alg_mean_bg = Alg_cell_bg{1}';
% Alg_mean_end = Alg_cell_end{1}';
figure;
subplot(2,2,1);
imagesc(Alg_mean_bg, 'xdata', [-wds_out, wds_in]/Fs);
ylabel('Cell(#)')
subplot(2,2,2);
imagesc(Alg_mean_end,'xdata', [-wds_in, wds_out]/Fs);
subplot(2,2,3);
plot([-wds_out:wds_in]/Fs, mean(Alg_mean_bg,1));
xlabel('Time from M-F begin(sec)'); ylabel('Average Calcuim Signal')
subplot(2,2,4);
plot([-wds_in:wds_out]/Fs, mean(Alg_mean_end,1));
xlabel('Time from M-F end (sec)'); 


function [Alg_mean, Alg_cell] = aligntoevents(data_chan_by_t, events, wds_L, wds_R)
nchan = size(data_chan_by_t, 1);
Alg_cell = cell(nchan,1);
Alg_mean = zeros(nchan, wds_R-wds_L+1);
for i=1:nchan
    wave = data_chan_by_t(i,:);
    Alg_sXtrail = BF_AlignWave2Tg(wave, events, wds_L, wds_R, false);
    Alg_cell{i} = Alg_sXtrail;
    Alg_mean(i,:) = mean(Alg_sXtrail, 2)';
end
    